layui.use(['layer','form','table','element','layedit','upload'],function () {
    var layer = layui.layer
        ,form = layui.form
        ,table =layui.table
        ,element = layui.element
        ,layedit = layui.layedit
        ,upload = layui.upload;

    //动态加载type和label
    $.ajax({
        type:"GET",
        url:"/admin/project/getLabelAndType",
        success:function (result) {
            var labelList = result.data.labelTypeList.labelList;
            var typeList = result.data.labelTypeList.typeList;

            $.each(labelList,function (i,label) {
                var labelName = label.labelName;
                var id = label.id;

                $("#labels").append("<input type='checkbox' name='label' title='"+labelName+"' value='"+id+"'></input>");
            })

            $.each(typeList,function (i,type) {
                var typeName = type.typeName;
                var id = type.id;

                //过滤免费项目无关的type
                if(typeName != "首页" && typeName != "包赔项目" && typeName != "投资赚钱" && typeName != "靠谱项目" && typeName !="最新项目"){
                    $("#types").append("<input type='checkbox' name='type' title='"+typeName+"' value='"+id+"'></input>");
                }

             })

            //重新渲染下拉框
            form.render();
        },
        error:function () {
            layer.msg("系统错误！");
        }
    });


    var index = layedit.build('addEdit', {
        tool: [
             'strong', 'italic', 'underline', 'del',
            ,'addhr' //添加水平线
            ,'|', 'fontFomatt','fontfamily','fontSize', //段落格式，字体样式，字体颜色
            , 'colorpicker', 'fontBackColor'//字体颜色，字体背景色
                    , 'face', '|', 'left', 'center', 'right', '|', 'link', 'unlink'
                    ,'image'//原版上传图片
                    ,'images'//多图上传
                    , 'image_alt'//上传图片拓展
                    ,'anchors' //锚点
                    , '|', 'table'//插入表格
                    ,'customlink'//插入自定义链接
                    ,'fullScreen'//全屏
            ]
        , height: 600
        ,   uploadImage: {
            url: '/admin/project/uploadProjectImg'
            ,type: 'post' //默认post
        }
    });


    //普通图片上传
    var uploadInst = upload.render({
        elem: '#update_cover_btn'
        ,url: '/admin/project/uploadImg'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#demo1').attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //如果上传失败
            console.log(res);
            var flag = res.flag;
            var message = res.message;
            if(!flag){
                layer.msg(message);
            }else{
                //上传成功,则返回url
                layer.msg("封面上传成功!");
                $("#cover_img").attr("value",res.data.url);
            }
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });

    //表单验证
    form.verify({
        summary:function (value) {
            if(value.length == 0){
                return "简介不能为空";
            }
            if(value.length>108){
                return "长度不能超过108，当前长度为"+value.length;
            }
        },
        id:function (value) {
            if(value == ""){
                return "id不能为空";
            }
        },
        cover:function (value) {
            if(value == ""){
                return "封面不能为空";
            }
        },
        content:function () {
            var content = layedit.getContent(index);
            if(content == "" || content.length==0){
                return "内容不能为空";
            }
        }
    });

        //提交表单
    form.on('submit(form)',function (data) {

        //校验类型和标签是否选择
        // var label_length = $("input[name=label]:checked").length;
        // var type_length = $("input[name=type]:checked").length;
        layer.msg('保存中...', { icon: 16, shade: [0.5, '#f5f5f5'], scrollbar: false, offset: '50%', time: 300000 });


        var labels = "";
        var types = "";

        $("input[name=label]:checked").each(function () {
            labels = labels + "," + $(this).val();
        });

        $("input[name=type]:checked").each(function () {
            types = types + "," + $(this).val();
        });

        if(labels == ""){
            layer.msg("请选择项目类型");
            return ;
        }
        if(types == ""){
            layer.msg("请选择项目标签");
            return;
        }

        labels = labels.substr(1,labels.length-1);
        types = types.substr(1,types.length-1);

        var paramData = {
                "title":$("#title").val(),
            "summary":$("#summary").val(),
            "cover":$("#cover_img").val(),
            "content":layedit.getContent(index),
            "labels":labels,
            "types":types,
            "commented":$("#commented").val(),
            "longTerm":$("#longTerm").val(),
            "profitFreeToday":$("#profitFreeToday").val()
        };

        var data2 = JSON.stringify(paramData);

        //保存项目
        $.ajax({
            url:"/admin/project/free_project_save",
            type:"POST",
            data:data2,
            // dataType:"json",
            contentType:"application/json;charset=utf-8",
            success:function (result) {
                // console.log("data=="+form_data)
                if(result.flag){
                    layer.msg(result.message);
                    //清空内容
                    // $("#form").reset();
                    document.getElementById("form").reset();
                    layui.form.render();
                }else{
                    layer.msg(result.message);
                }
            },
            error:function () {
                layer.msg("系统错误！");
            }
        });

    });

    // layedit.setContent(index, "<h1 style='color: red'>hahahha</h1>");

    // $('#submitBtn').click(function () {
    //     //获取编辑器的值
    //     var content = layedit.getContent(index);
    //
    //     alert(content);
    // });


});
